package cn.ywang;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Auther: BeatificWang
 * @Date: 2018/11/3 10:28
 */
@Slf4j
public class Client {

	private final int DEFAULT_SERVER_PORT = 8888;

	private final String DEFAULT_SERVER_IP = "127.0.0.1";

	private String name;

	public Client(String name) {
		this.name = name;
	}


	public void send(String content) {
		this.send(this.DEFAULT_SERVER_PORT, content);
	}

	private void send(int port, String content) {
		System.out.println(this.name + "：" + content);
		Socket socket = null;
		BufferedReader reader = null;
		PrintWriter writer = null;
		try {
			socket = new Socket(this.DEFAULT_SERVER_IP, port);
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new PrintWriter(socket.getOutputStream(), true);
			writer.println(content);
			log.info(this.name + "：" + content);
			System.out.println("服务器端:" + reader.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				reader = null;
			}
			if (writer != null) {
				writer.close();
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				socket = null;
			}
		}

	}

}
